import React, {useEffect} from 'react';
import {ModalHeader, Modal, ModalFooter, Col, Row, ModalBody, Button} from "reactstrap";
import * as Icon from "react-feather"
import {
  SET_CONTACT_FIELD as SET_EVENT_CONTACT_FIELD,
  UNSET_CONTACT_FIELD
} from "../../../../../../redux/constants/eventDetail/tabContacts";
import {connect} from "react-redux";
import {setFieldData, setNotification} from "../../../../../../redux/actions/helper";
import {
  deleteContact,
  getContact,
  UpdateContact,
  storeContact
} from "../../../../../../redux/actions/eventDetail/tabContacts";
import {getContacts} from "../../../../../../redux/actions/contacts";
import Select, {components} from "react-select";
import {SET_CONTACT_FIELD} from "../../../../../../redux/constants/contacts";
import chroma from "chroma-js";


const AddForm = (props) => {
  const {contact, contacts, params, reqParams, contactsGlobal, eventId, reqParamsContact} = props
  const {setFieldData, getContact, getContacts, deleteContact, UpdateContact, storeContact, setNotification} = props

  const Save = () => {
    if (contact.id)
      if (params.contact_id)
        UpdateContact(contact, eventId)
      else storeContact(contact, eventId)
    else setNotification('Выберите контакт', 'error')
  }

  const contactsFilter = () => {
    const contactsArray = contacts.map(contact => contact.id)
    return [{value: -1, label: 'Добавить контакт'}].concat(contactsGlobal.filter(contact => {
      return contactsArray.indexOf(contact.id) === -1
    }).map(value => {
        return {
          ...value,
          value: value.id,
          label: value.name
        }
      }
    ))
  }
  const Delete = () => {
    deleteContact(params.contact_id, eventId)
  }

  const contactChange = (e) => {
    if (e.value === -1)
      setFieldData(SET_CONTACT_FIELD, 'params', {
        ...params,
        contact_id: null,
        isOpenModal: true
      })
    else
      setFieldData(SET_EVENT_CONTACT_FIELD, 'contact', {...contact, ...e})
  }

  const Option = props => {
    return (
      props.data.value !== -1 ? <components.Option {...props} /> :
        <components.Option {...props} >
          <div className='d-flex justify-content-between align-items-center'>
            <p className='m-0'>{props.data.label}</p>
            <Icon.Plus size={18}/>
          </div>
        </components.Option>
    );
  };

  const toggleModal = () => {
    setFieldData(SET_EVENT_CONTACT_FIELD, 'params', {
      ...params,
      contact_id: null,
      isOpenModal: false
    })
    setFieldData(UNSET_CONTACT_FIELD, '', {})
  }

  const setContactValue = (payload) => {
    setFieldData(SET_EVENT_CONTACT_FIELD, 'contact', {...contact, ...payload})
  }


  useEffect(() => {
    if (params.isOpenModal)
      if (params.contact_id) {
        getContact(params.contact_id, {...reqParams, event_id: eventId}, params)
      } else {
        setFieldData(UNSET_CONTACT_FIELD, '', {})
      }
  }, [params.isOpenModal])

  useEffect(() => {
    if (params.isOpenModal)
      getContacts(reqParamsContact)
  }, [params.isOpenModal])


  return (
    <React.Fragment>
      <Modal
        isOpen={params.isOpenModal}
        toggle={toggleModal}
        size={'lg'}
      >
        <ModalHeader toggle={toggleModal}>
          {params.contact_id ? 'Редактировать контакт' : 'Добавить контакт'} <Icon.UserPlus size={20}/>
        </ModalHeader>
        <ModalBody className={'p-2'}>
          <Row>
            <Col lg={4} className="mt-1 d-flex align-items-center">
              <h5 className={'m-0'}>Контакт</h5>
            </Col>
            <Col lg={6} className="mt-1">
              <Select
                isDisabled={params.contact_id}
                className={`contacts-item contacts-input-select`}
                classNamePrefix="dark_select"
                value={{value: contact.id, label: contact.name}}
                options={contactsFilter()}
                isSearchable={false}
                onChange={contactChange}
                name='typesList'
                components={{Option}}
              />
            </Col>
          </Row>
          <Row>
            <Col lg={4} className="mt-1 d-flex align-items-center">
              <h5 className={'m-0'}>Позиция</h5>
            </Col>
            <Col lg={8} className="mt-1">
              <input
                value={contact.position || ''}
                onChange={(e) => setContactValue({position: e.target.value})}
                className={`contacts-item contacts-input`}/>
            </Col>
          </Row>

        </ModalBody>
        <ModalFooter>
          {
            params.contact_id && <Button.Ripple onClick={Delete} color="danger" className="btn-uppercase">
              Удалить
            </Button.Ripple>
          }
          <Button.Ripple color="primary" onClick={Save} className="btn-uppercase">
            Сохранить
          </Button.Ripple>
        </ModalFooter>
      </Modal>
    </React.Fragment>
  )
}

const mapStateToProps = state => ({
  contact: state.eventContacts.contact,
  contactsGlobal: state.contacts.contacts,
  contacts: state.eventContacts.contacts,
  params: state.eventContacts.params,
  reqParams: state.eventContacts.reqParams,
  reqParamsContact: state.contacts.reqParams
})

export default connect(mapStateToProps, {
  setFieldData, getContact, getContacts, deleteContact, UpdateContact, storeContact, setNotification
})(AddForm);
